package logic

import (
	"context"
	"fmt"
	"taobao/cache"
	"taobao/model"

	"taobao/taobaorpc/internal/svc"
	"taobao/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *taobaorpc.CartAddRequest) (*taobaorpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	var product model.Product
	err := product.FindProductId(model.DB, in.ProductId)
	if err != nil {
		return nil, err
	}
	if product.ID == 0 {
		return nil, fmt.Errorf("商品异常不能添加到购物车")
	}
	if product.Stock < in.Number {
		return nil, fmt.Errorf("商品库存不足无法加入购物车")
	}
	key := fmt.Sprintf("cart:%d:%d", in.UserId, in.ProductId)
	result, _ := cache.Rdb.Exists(l.ctx, key).Result()
	if result == 0 {
		m := map[string]interface{}{
			"userId":    in.UserId,
			"productId": in.ProductId,
			"number":    in.Number,
			"name":      product.Name,
			"price":     product.Price,
		}
		cache.Rdb.HMSet(l.ctx, key, m)
	} else {
		cache.Rdb.HIncrBy(l.ctx, key, "number", in.Number)
	}
	return &taobaorpc.CartAddResponse{
		ProductId: in.ProductId,
	}, nil
}
